<template>
  <div id="homepage-wrapper">
    <Spin fix v-if="spinShow" style="z-index:1999"></Spin>
    <div class="content flex center stretch">
      <!-- 左侧栏 -->
      <div class="left-content shadow">
        <div class="fixed">
          <div class="top-title">微信扫码预览</div>
          <div class="qcode-wrapper" :style="`background-image: url('${qrcode}');`"></div>
          <div class="flex center column-center for-column">
            <p style="font-size:12px;color:black;margin-right: 10px;margin-bottom: 18px">
              页面路径：
              <span id="urlText">{{preview_path}}</span>
            </p>
            <Row type="flex" justify="center" style="margin-bottom: 20px">
              <Button
                type="primary"
                size="small"
                class="copyBtn"
                data-clipboard-target="#urlText"
                @click="copyUrl"
                style="padding: 3px 20px 3px 20px;"
              >复制地址</Button>
            </Row>
          </div>
        </div>

        <div style="width:250px;height:16px;background:#F5F5F5"></div>
        <div class="flex flex-wrap component-wrapper center column-center">
          <!-- <p>添加新的组件</p>
                    <Row style='padding: 20px 0;'>
                        <template v-for="item in components">
                            <Col span="8">
                                <div class="item-wrapper">
                                    <Button type="primary" size="default" ghost @click.native='addComponent(item.type,item.title)'>{{item.title}}</Button>
                                </div>
                            </Col>
                        </template>
          </Row>-->
          <div class="component-title">
            <div
              class="title-block"
              @click="dealSpread('spreadFirst')"
              :style="spreadFirst?'':'border-bottom:1px solid #EEEEEE;padding-bottom: 5px;'"
            >
              <div class="title">基础组件</div>
              <Icon v-if="spreadFirst" type="ios-arrow-down" size="20" color="#999999"/>
              <Icon v-else type="ios-arrow-up" size="20" color="#999999"/>
            </div>
          </div>
          <div class="component-con" v-if="spreadFirst">
            <div
              class="con-block"
              v-for="item in components.basics"
              @click="addComponent(item.type,item.title)"
            >
              <div class="title-block">
                <div class="title">{{item.title}}</div>
                <Tooltip max-width="200" :content="item.tooltip">
                  <Icon type="ios-help-circle-outline" size="16"/>
                </Tooltip>
              </div>
              <img :src="item.imgSrc" class="con-img">
            </div>
          </div>
          <div class="component-title">
            <div
              class="title-block"
              @click="dealSpread('spreadSecond')"
              :style="spreadSecond?'':'border-bottom:1px solid #EEEEEE;padding-bottom: 5px;'"
            >
              <div class="title">商品组件</div>
              <Icon v-if="spreadSecond" type="ios-arrow-down" size="20" color="#999999"/>
              <Icon v-else type="ios-arrow-up" size="20" color="#999999"/>
            </div>
          </div>
          <div class="component-con" v-if="spreadSecond">
            <div
              class="con-block"
              v-for="item in components.commodity"
              @click="addComponent(item.type,item.title)"
            >
              <div class="title-block">
                <div class="title">{{item.title}}</div>
                <Tooltip max-width="200" :content="item.tooltip">
                  <Icon type="ios-help-circle-outline" size="16"/>
                </Tooltip>
              </div>
              <img :src="item.imgSrc" class="con-img">
            </div>
          </div>
          <div class="component-title">
            <div
              class="title-block"
              @click="dealSpread('spreadThird')"
              :style="spreadThird?'':'border-bottom:1px solid #EEEEEE;padding-bottom: 5px;'"
            >
              <div class="title">营销组件</div>
              <Icon v-if="spreadThird" type="ios-arrow-down" size="20" color="#999999"/>
              <Icon v-else type="ios-arrow-up" size="20" color="#999999"/>
            </div>
          </div>
          <div class="component-con" v-if="spreadThird">
            <div
              class="con-block"
              v-for="item in components.marketing"
              @click="addComponent(item.type,item.title)"
            >
              <div class="title-block">
                <div class="title">{{item.title}}</div>
                <Tooltip max-width="200" :content="item.tooltip">
                  <Icon type="ios-help-circle-outline" size="20"/>
                </Tooltip>
              </div>
              <img :src="item.imgSrc" class="con-img">
            </div>
          </div>
        </div>
      </div>
      <!-- 中间预览栏 -->
      <div class="middle-content shadow">
        <div class="component-detail" ref="componentDetail">
          <!-- 微页面顶部标题 -->
          <div @click="getTopTitleData">
            <top-title-module
              v-if="this.micro_id != 'index'"
              :active="label_index==-1"
              :top-title="microTopTitle"
            />
          </div>

          <draggable v-model="componentList" @end="endDrag" :options="{animation: 150}">
            <transition-group>
              <div
                v-for="(item,index) in componentList"
                :key="'component'+index"
                @click="selectComponent(index,item.label_type,item.label_id)"
              >
                <!-- 轮播组件 -->
                <banner-module
                  v-if="item.label_type=='bannerChannel'"
                  :active="label_index==index"
                  :module-data="item"
                  @delModule="delModule"
                />
                <!-- 快速入口 -->
                <activity-module
                  v-if="item.label_type=='activityChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 普通组件-->
                <normal-module
                  v-if="item.label_type=='normalChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 商品列表组件-->
                <goods-list-module
                  v-if="item.label_type=='goodsList'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 秒杀组件 -->
                <second-kill-module
                  v-if="item.label_type=='secKillChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 拼团组件 -->
                <group-module
                  v-if="item.label_type=='hotFightGroupChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 达人卡片 -->
                <talent-module
                  v-if="item.label_type=='talentChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 图片组件 -->
                <image-module
                  v-if="item.label_type=='imageCardChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 商品合辑 -->
                <goods-album-module
                  v-if="item.label_type=='goodsAlbumChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 搜索组件 -->
                <search-module
                  v-if="item.label_type=='searchChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 文本组件 -->
                <text-module
                  v-if="item.label_type=='textChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 滑动组件 -->
                <slider-module
                  v-if="item.label_type=='slideChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 榜单组件 -->
                <rank-module
                  v-if="item.label_type=='rankChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 分类组件 -->
                <class-module
                  v-if="item.label_type=='classChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 悬浮组件 -->
                <suspension-module
                  v-if="item.label_type=='merchantEntryChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 抽奖组件 -->
                <lottery-module
                  v-if="item.label_type=='lotteryChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />

                <!-- 距离组件 -->
                <DistanceChannelModule
                  v-if="item.label_type=='distanceChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 公告组件 -->
                <NoticeModule
                  v-if="item.label_type=='notifyChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
                <!-- 砍价组件 -->
                <bargainModule
                  v-if="item.label_type=='bargainChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />

                <!-- H5抽奖组件 -->
                <LuckdrawModule
                  v-if="item.label_type=='H5LotteryChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />

                <!-- 弹窗组件 -->
                <PopupModule
                  v-if="item.label_type=='popupChannel'"
                  :module-data="item"
                  :active="label_index==index"
                  @delModule="delModule"
                />
              </div>
            </transition-group>
          </draggable>
        </div>
      </div>
      <!-- 右侧详情栏 -->
      <div class="right-content shadow">
        <Spin fix v-if="spinRightContentShow" style="z-index:1999"></Spin>
        <!-- 编辑组件 -->
        <edit-common-module :module-data="compomentOneData" @save="saveEdit"/>
      </div>
    </div>
  </div>
</template>

<script>
import Config from "@/config";

import Clipboard from "clipboard";

import * as compareVersions from 'compare-versions';

import {
  getOnlineVersion,
  getPreviewData,
  getQrcode,
  updateModule,
  removeModule,
  getOneModule,
  updateEdit,
  updatePage,
  addModule,
  getPageData
} from "api/shopDecoration";

import { getCache } from "common/js/util";

// 拖动插件
import draggable from "vuedraggable";
//微页面顶部标题组件
import TopTitleModule from "./components/TopTitleModule/TopTitleModule";

// 轮播组件
import BannerModule from "./components/BannerModule/BannerModule";
// 快速入口
import ActivityModule from "./components/ActivityModule/ActivityModule";
// 普通组件
import NormalModule from "./components/NormalModule/NormalModule";
// 商品列表组件
import GoodsListModule from "./components/GoodsListModule/GoodsListModule";
// 秒杀组件
import SecondKillModule from "./components/SecondKillModule/SecondKillModule";
// 拼团组件
import GroupModule from "./components/GroupModule/GroupModule";
// 达人卡片
import TalentModule from "./components/TalentModule/TalentModule";
// 图片组件
import ImageModule from "./components/ImageModule/ImageModule";
// 商品合辑
import GoodsAlbumModule from "./components/GoodsAlbumModule/GoodsAlbumModule";
// 搜索组件
import SearchModule from "./components/SearchModule/SearchModule";
// 文本组件
import TextModule from "./components/TextModule/TextModule";
// 滑动组件
import SliderModule from "./components/SliderModule/SliderModule";
// 榜单组件
import RankModule from "./components/RankModule/RankModule";
// 分类组件
import ClassModule from "./components/ClassModule/ClassModule";
// 悬浮组件
import SuspensionModule from "./components/SuspensionModule/SuspensionModule";
// 抽奖组件
import LotteryModule from "./components/LotteryModule/LotteryModule";
// 距离组件
import DistanceChannelModule from "./components/DistanceChannelModule/DistanceChannelModule";
// 公告组件
import NoticeModule from "./components/NoticeModule/NoticeModule";
// 砍价组件
import bargainModule from "./components/bargainModule/bargainChannelModule";
// 抽奖组件
import LuckdrawModule from "./components/LuckdrawModule/LuckdrawModuleModule";
// 编辑组件
import EditCommonModule from "./components/EditCommonModule/EditCommonModule";
// 弹窗组件
import PopupModule from "./components/PopupModule/PopupModule";

export default {
  data() {
    return {
      // 预览二维码
      qrcode: "",

      // 预览loading
      spinShow: false,
      // 右边组件详情预览loading
      spinRightContentShow: false,

      // 组件详情数据
      compomentOneData: {},

      // 选中的模块类型
      label_type: "",
      // 选中的模块索引 -1选中微页面顶部标题
      label_index: 0,
      // 选中模块id
      label_id: 0,

      // 模块数据数组
      componentList: [],

      // 微页面顶部标题
      microTopTitle: "（标题）未设置",

      // 可添加模块数据
      components: [],

      midComponents: [
        {
          title: "轮播图",
          type: "bannerChannel"
        },
        {
          title: "快速入口",
          type: "activityChannel"
        },
        {
          title: "普通组件",
          type: "normalChannel"
        },
        {
          title: "秒杀组件",
          type: "secKillChannel"
        },
        {
          title: "大图组件",
          type: "hotFightGroupChannel"
        },
        {
          title: "达人卡片",
          type: "talentChannel"
        },
        {
          title: "图片组件",
          type: "imageCardChannel"
        },
        {
          title: "商品合辑",
          type: "goodsAlbumChannel"
        },
        // {
        //   title: "弹窗组件",
        //   type: "popupChannel"
        // }
      ],

      //组件展开
      spreadFirst: true,
      spreadSecond: true,
      spreadThird: true
    };
  },
  methods: {
    // 复制链接
    copyUrl() {
      let clipboard = new Clipboard(".copyBtn");
      clipboard.on("success", e => {
        this.$Message.success("复制成功！");
        clipboard.destroy();
      });
      clipboard.on("error", e => {
        this.$Message.error("复制失败，请更换浏览器或者手动复制");
        clipboard.destroy();
      });
    },

    // 拖拽停止
    endDrag: function(event) {
      // 拼装组件id数组
      var labelIds = "";
      for (var i = 0; i < this.componentList.length; i++) {
        labelIds += this.componentList[i].label_id;
        if (i < this.componentList.length - 1) {
          labelIds += ",";
        }
      }
      // 请求接口 更新组件位置
      updateModule({ parent: this.micro_id, labels: labelIds })
        .then(_res => {
          this.$Message.success("更新组件成功");
        })
        .catch(err => {
          this.$Message.error(err.message);
        });
    },

    // 获取组件详细数据
    getModuleData(label_id, label_type) {
      this.spinRightContentShow = true;
      getOneModule({ labelId: label_id })
        .then(_res => {
          this.spinRightContentShow = false;
          let compomentOneData = {};
          compomentOneData["data"] = _res.data;
          compomentOneData["type"] = label_type;
          this.compomentOneData = compomentOneData;
          if (label_type == "textChannel") {
            eventBus.$emit("uechose");
          }
        })
        .catch(err => {
          this.spinRightContentShow = false;
          this.$Message.error(err.message);
        });
    },

    // 点击组件事件
    selectComponent(index, label_type, label_id) {
      this.label_index = index;
      this.label_type = label_type;
      this.label_id = label_id;
      // 获取组件数据
      this.getModuleData(label_id, label_type);
    },

    // 获取微页面顶部标题数据
    getTopTitleData() {
      this.label_index = -1;
      getPageData({ labelId: this.micro_id })
        .then(_res => {
          if (!_res.data.json) {
            _res.data.json = {
              image_path: "",
              share_image: "",
              text: ""
            };
          }
          this.microTopTitle = _res.data.label_name_cn;
          var compomentOneData = {};
          compomentOneData["data"] = _res.data;
          compomentOneData["data"].version = this.version;
          compomentOneData["type"] = "topTitleChannel";
          this.compomentOneData = compomentOneData;
        })
        .catch(err => {
          this.$Message.error(err.message);
        });
    },

    // 添加组件
    addComponent(type, title) {
      var that = this;
      this.$Modal.confirm({
        title: "提示",
        content: "是否要添加该组件吗？",
        onOk: () => {
          addModule({ parent: this.micro_id, labelType: type })
            .then(_res => {
              that.$Message.success("添加组件成功");
              getPreviewData({ labelId: this.micro_id })
                .then(_res => {
                  that.componentList = _res.data;
                  that.label_index = that.componentList.length - 1;
                  // 滚动到底部
                  setTimeout(function() {
                    that.$refs.componentDetail.scrollTop =
                      that.$refs.componentDetail.scrollHeight;
                  }, 250);
                })
                .catch(err => {
                  that.$Message.error(err.message + " 请重新刷新页面");
                });
              that.getModuleData(_res.data, type);
            })
            .catch(err => {
              that.$Message.error(err.message);
            });
        }
      });
    },

    // 删除组件回调
    delModule(moduleData) {
      if (this.componentList.length == 1) {
        this.$Message.error("请最少保留一个组件");
        return false;
      }
      var that = this;
      this.$Modal.confirm({
        title: "提示",
        content: "是否要删除该组件",
        onOk: () => {
          that.spinShow = true;
          removeModule({ parent: this.micro_id, labelId: moduleData.label_id })
            .then(_res => {
              that.spinShow = false;
              that.$Message.success("删除组件成功");
              // 移除删除数据项
              var index = that.componentList.indexOf(moduleData);
              if (index > -1) {
                that.componentList.splice(index, 1);
              }
              that.label_index = index == 0 ? 0 : index - 1;
              that.label_id = that.componentList[that.label_index].label_id;
              // 重新获取组件数据
              that.getModuleData(
                that.label_id,
                that.componentList[that.label_index].label_type
              );
            })
            .catch(err => {
              that.spinShow = false;
              that.$Message.error(err.message);
            });
        }
      });
    },

    // 获取数据
    getData() {
      var that = this;
      that.spinShow = true;
      this.components = this.midComponents.concat();

      // 版本控制组件
      let req1 = getOnlineVersion()
        .then(_res => {
          this.version = _res.data.onlineVersion;
          if (this.version == "") {
            // 审核中 开放全部组件
            this.components.push(
              {
                title: "搜索组件",
                type: "searchChannel"
              },
              {
                title: "悬浮组件",
                type: "merchantEntryChannel"
              },
              {
                title: "文本组件",
                type: "textChannel"
              },
              {
                title: "滑动组件",
                type: "slideChannel"
              },
              {
                title: "榜单组件",
                type: "rankChannel"
              },
              {
                title: "分类组件",
                type: "classChannel"
              }
            );

            // if (this.micro_id == "index") {
            //     this.components.push({
            //         title: '分类组件',
            //         type: 'classChannel'
            //     })
            // } else {
            //     this.wechatAppid = getCache("wechat_app_id");
            //     if (this.wechatAppid == "wx8f658b1c23012392" || this.wechatAppid=="wx638f492187c8bfb2") {
            //         this.components.push({
            //             title: '分类组件',
            //             type: 'classChannel'
            //         })
            //     }
            // }
            this.components.push({
              title: "抽奖组件",
              type: "lotteryChannel"
            });
          } else {
            this.components.push({
              title: "H5砍价",
              type: "bargainChannel"
            });
            this.components.push({
              title: "H5抽奖",
              type: "H5LotteryChannel"
            });
            this.wechatAppid = getCache("wechat_app_id");
            let popupVersion = '4.38.0311'
            if (this.wechatAppid=="wx8f658b1c23012392" || this.wechatAppid=='wx1e7392986800c1dd' || compareVersions(this.version, popupVersion) >= 0) {
                this.components.push(
                    {
                        title: '弹窗组件',
                        type: 'popupChannel'
                    },
                )
            }
            if (this.compareVersion(this.version, "4.29.0114")) {
              this.components.push({
                title: "距离组件",
                type: "distanceChannel"
              });
            }
            if (this.compareVersion(this.version, "4.1.0725")) {
              this.components.push(
                {
                  title: "搜索组件",
                  type: "searchChannel"
                },
                {
                  title: "悬浮组件",
                  type: "merchantEntryChannel"
                }
              );
            }
            if (this.compareVersion(this.version, "4.4.0807")) {
              this.components.push(
                {
                  title: "文本组件",
                  type: "textChannel"
                },
                {
                  title: "滑动组件",
                  type: "slideChannel"
                },
                {
                  title: "榜单组件",
                  type: "rankChannel"
                },
                {
                  title: "分类组件",
                  type: "classChannel"
                }
              );
              // if (this.micro_id == "index") {
              //     this.components.push({
              //         title: '分类组件',
              //         type: 'classChannel'
              //     })
              // } else {
              //     this.wechatAppid = getCache("wechat_app_id");
              //     if (this.wechatAppid == "wx8f658b1c23012392" || this.wechatAppid=="wx638f492187c8bfb2") {
              //         this.components.push(
              //             {
              //                 title: '分类组件',
              //                 type: 'classChannel'
              //             },
              //         )
              //     }
              // }
            }
            if (this.compareVersion(this.version, "4.7.0828")) {
              this.components.push({
                title: "抽奖组件",
                type: "lotteryChannel"
              });
            }

            if (this.compareVersion(this.version, "4.25.1227")) {
              this.components.push({
                title: "公告组件",
                type: "notifyChannel"
              });
            }
          }
          this.dealComponents(this.components);
        })
        .catch(err => {
          this.$Message.error(err.message);
        });

      // 预览数据
      let req2 = getPreviewData({ labelId: this.micro_id })
        .then(_res => {
          that.componentList = _res.data;
          if (that.micro_id != "index") {
            // 微页面直接获取顶部标题数据
            that.getTopTitleData();
          } else {
            if (that.componentList.length == 0) {
              return;
            }
            //  首页直接获取第一个模块数据
            that.label_id = that.componentList[that.label_index].label_id;
            this.getModuleData(
              that.label_id,
              that.componentList[that.label_index].label_type
            );
          }
        })
        .catch(err => {
          this.$Message.error(err.message + " 请重新刷新页面");
        });

      // 获取二维码
      let req3 = getQrcode({ qrcodePath: this.preview_path })
        .then(_res => {
          this.qrcode = _res.data.qrcodePath;
        })
        .catch(err => {
          this.$Message.error(err.message);
        });

      // 执行完后关闭loading
      Promise.all([req1, req2, req3])
        .then(function(res) {
          that.spinShow = false;
        })
        .catch(err => {
          that.$Message.error(err.message ? err.message : "请求失败");
          that.spinShow = false;
        });
    },
    //对自定义组件进行分类处理
    dealComponents(data) {
      let that = this;
      var newComponents = new Object();
      newComponents.basics = new Array();
      newComponents.commodity = new Array();
      newComponents.marketing = new Array();
      for (let i = 0; i < data.length; i++) {
        var tempData = new Object();
        tempData.title = data[i].title;
        tempData.type = data[i].type;
        switch (data[i].type) {
          case "bannerChannel": //轮播图
            tempData.num = 1;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055730430400.png";
            tempData.tooltip =
              "轮播图组件作为大图组件之首，除了商品图片能展示得更大外，同时支持商品自动轮换播放，在小的空间里展示更多商品，常装修于页面顶部，相对其他组件吸睛，不管任何商品乃至活动页面入口皆可以关联，同时支持第三方小程序跳转，亦可以创造广告营收";
            newComponents.commodity.push(tempData);
            break;
          case "activityChannel": //快速入口
            tempData.num = 2;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055948674358.png";
            tempData.tooltip =
              "快速入口组件属于图标类组件，支持自定义上传图标图片、自定义排序，一行最高支持6个图标，快速入口组件有图有文，常用于跟微页面关联，更加形象的突出页面入口";
            newComponents.basics.push(tempData);
            break;
          case "normalChannel": //普通组件
            tempData.num = 3;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055952589767.png";
            tempData.tooltip =
              "普通组件是最常用的组件之一，小小的商品图片能让页面尽可能地展示更多商品，同时能展示商品的主要信息，包括标题、售价、原价，支持显示“查看更多”按钮关联微页面或指定商品";
            newComponents.commodity.push(tempData);
            break;
          case "secKillChannel": //秒杀组件
            tempData.num = 1;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055956345291.png";
            tempData.tooltip =
              " 秒杀组件展示方式与滑动组件保持一致，装修时无需选择商品，系统能自动把所有秒杀商品展示于组件上，并且默认开启“查看更多”按钮，点击按钮可进入秒杀活动专属页面";
            newComponents.marketing.push(tempData);
            break;
          case "hotFightGroupChannel": //大图组件
            tempData.num = 2;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/20/155065328132248.png";
            tempData.tooltip =
              "大图组件原为拼团专属组件，后迭代为大图组件，支持除H5抽奖、砍价商品的其余所有类型商品展示，与商品列表组件有点像，商品信息结构的表现方式不同，同样的是提高阅读体验，更直观看到商品信息";
            newComponents.commodity.push(tempData);
            break;
          case "talentChannel": //达人卡片
            tempData.num = 5;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055963466486.png";
            tempData.tooltip =
              "达人组件具有网红营销作用，与商品或微页面关联，可以制造网红推荐效果，打造IP营销，信任值更高，用户更愿意为此类商品买单";
            newComponents.basics.push(tempData);
            break;
          case "imageCardChannel": //图片组件
            tempData.num = 4;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055966443774.png";
            tempData.tooltip =
              "图片组件功能强大，拥有16种滤镜叠加效果可自定义选择，支持不同尺寸的图片展示，表现方式灵活";
            newComponents.basics.push(tempData);
            break;
          case "goodsAlbumChannel": //商品合辑
            tempData.num = 6;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055972147646.png";
            tempData.tooltip =
              "合辑组件多用于活动商品汇合，为商品打造活动效果/专区效果，用户对合辑组件上的商品更容易快速地理解为活动商品";
            newComponents.commodity.push(tempData);
            break;
          case "searchChannel": //搜索组件
            tempData.num = 1;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055974717885.png";
            tempData.tooltip =
              "搜索组件在各大电商乃至社交等平台都很常见，半城云支持自定义搜索显示文案，搜索组件除了可以装修在页面顶部以外，还可以装修在页面底部，适用于呈现比较多商品页面，应用场景：当用户把页面浏览到底部还没有找到心仪的商品，即可在底部进行搜索商品，精准购物";
            newComponents.basics.push(tempData);
            break;
          case "merchantEntryChannel": //悬浮组件
            tempData.num = 6;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055977677488.png";
            tempData.tooltip =
              "悬浮组件作为全局显示的组件，悬浮页面右下角，多作为“企业入驻”和“客服”入口，可自定义按钮显示名称，支持文案编辑显示、一键拨号、一键复制微信号";
            newComponents.basics.push(tempData);
            break;
          case "distanceChannel": //距离组件
            tempData.num = 7;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/20/155065318117664.png";
            tempData.tooltip =
              "距离组件属于大图组件的升级版，相比大图组件增加企业距离显示和附近商品显示，场景化更高，平台给到用户更智能化的感觉，用户体验更好";
            newComponents.commodity.push(tempData);
            break;
          case "textChannel": //文本组件
            tempData.num = 7;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055985736318.png";
            tempData.tooltip =
              "文本组件支持展示图文，多用于介绍平台、企业，也可用于平台公告，比较特殊的用法是微页面充当店铺或活动主页，利用文本组件进行图文排版介绍，亦可置于首页顶部，引导用户操作“添加到我的小程序”";
            newComponents.basics.push(tempData);
            break;
          case "slideChannel": //滑动组件
            tempData.num = 5;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055989470950.png";
            tempData.tooltip =
              "滑动组件交互方式主要以左滑动作来浏览商品，让小程序的交互不再单调，同时商品展示信息与普通组件保持一致，同样支持显示“查看更多”按钮关联微页面或指定商品";
            newComponents.commodity.push(tempData);
            break;
          case "rankChannel": //榜单组件
            tempData.num = 7;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055992977399.png";
            tempData.tooltip =
              "榜单组件支持显示最少5个、最多10个商品或企业显示，并且支持排序设置，商品上架于榜单组件的热销效果更强，如果做企业榜单还可以为企业店铺主页引流，促进企业店铺的商品消费";
            newComponents.commodity.push(tempData);
            break;
          case "classChannel": //分类组件
            tempData.num = 3;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155055999388902.png";
            tempData.tooltip =
              "分类组件装修常见于页面顶部，用户进入页面即可以看到分类，用户进入单品类页面后精准购物，分类组件支持滑动选择，操作体验更为新颖";
            newComponents.basics.push(tempData);
            break;
          case "lotteryChannel": //抽奖组件
            tempData.num = 2;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155056001432682.png";
            tempData.tooltip =
              "抽奖组件作为秒抽奖商品的专属组件，主要提供抽奖商品的专属大图列表，展示赞助、价值、参与人数等信息，支持“查看更多”按钮设置";
            newComponents.marketing.push(tempData);
            break;
          case "notifyChannel": //公告组件
            tempData.num = 8;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/19/155056006220801.png";
            tempData.tooltip =
              "公告组件具有通知作用，置顶让更多用户进入首页即可以看到，相应的文案可以制造库存紧张、紧急气氛，如：最后xx杯、xx即将售罄、xx抢购即将开始等";
            newComponents.basics.push(tempData);
            break;
          case "goodsList": //商品列表
            tempData.num = 8;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/20/155065328132248.png";
            tempData.tooltip =
              "商品列表组件属于大图组件，提高阅读体验，更直观看到商品信息，目前仅在微页面装修，支持商品自定义排序，可以创造权重营收";
            newComponents.commodity.push(tempData);
            break;
          case "bargainChannel": //H5砍价
            tempData.num = 4;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/21/155071595841877.png";
            tempData.tooltip =
              "H5砍价组件为H5专属组件，主要提供砍价商品列表展示，支持显示剩余数量、参与数据，营造活动效果，助力吸粉";
            newComponents.marketing.push(tempData);
            break;
            break;
          case "H5LotteryChannel": //H5抽奖
            tempData.num = 3;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/21/155071647122502.png";
            tempData.tooltip =
              "H5抽奖组件同样为H5专属组件，主要提供抽奖商品列表展示，支持显示开奖方式及参与数据，营造活动效果，助力裂变传播、吸粉";
            newComponents.marketing.push(tempData);
            break;
          case "popupChannel": //弹窗组件
            tempData.num = 5;
            tempData.imgSrc =
              "https://file.open.banchengyun.com/2019/02/27/155125538088673.png";
            tempData.tooltip =
              "弹窗组件是最常用的营销组件，多用于活动预告，弹窗以图片为显示内容，自定义显示的灵活性更高，支持设置显示活动倒计时，更利于制造活动紧张感";
            newComponents.marketing.push(tempData);
            break;
          default:
            console.log("default");
            break;
        }
      }

      //自定义组件排序
      for (let j in newComponents) {
        for (let s1 = 0; s1 < newComponents[j].length - 1; s1++) {
          for (let s2 = 0; s2 < newComponents[j].length - 1 - s1; s2++) {
            if (newComponents[j][s2].num > newComponents[j][s2 + 1].num) {
              var temp = newComponents[j][s2 + 1];
              newComponents[j][s2 + 1] = newComponents[j][s2];
              newComponents[j][s2] = temp;
            }
          }
        }
      }
      that.components = newComponents;
    },
    //处理组件栏收缩
    dealSpread(type) {
      let that = this;
      if (type == "spreadFirst") {
        if (that.spreadFirst) {
          that.spreadFirst = false;
        } else {
          that.spreadFirst = true;
        }
      } else if (type == "spreadSecond") {
        if (that.spreadSecond) {
          that.spreadSecond = false;
        } else {
          that.spreadSecond = true;
        }
      } else if (type == "spreadThird") {
        if (that.spreadThird) {
          that.spreadThird = false;
        } else {
          that.spreadThird = true;
        }
      }
    },
    // 保存编辑数据
    saveEdit(data) {
      let that = this;
      var parms = {};
      parms.label_type = data.label_type;
      parms.label_id = data.label_id;
      parms.label_info_summary = data.label_info_summary;
      parms.label_goods = data.label_goods;
      parms.label_name_cn = data.label_name_cn;
      parms.label_display_times = data.label_display_times;
      // parms.show_shops = data.show_shops;

      parms.json = JSON.stringify(data.json);

      if (data.updatePage) {
        if (parms.label_name_cn == "") {
          this.$Message.error("页面标题不能为空");
          return;
        }
        that.spinShow = true;
        updatePage(parms)
          .then(_res => {
            this.$Message.success("保存页面基本信息成功");
            getPreviewData({ labelId: this.micro_id })
              .then(_res => {
                that.spinShow = false;
                this.componentList = _res.data;
              })
              .catch(err => {
                that.spinShow = false;
                this.$Message.error(err.message + " 请重新刷新页面");
              });
          })
          .catch(err => {
            that.spinShow = false;
            this.$Message.error(err.message);
          });
      } else {
        // 判断跳转填写信息是否完整
        if (
          parms.label_type == "activityChannel" ||
          parms.label_type == "bannerChannel" ||
          parms.label_type == "imageCardChannel" ||
          parms.label_type == "classChannel"
        ) {
          // 快速入口 轮播组件 图片组件
          for (let i = 0; i < data.json.length; i++) {
            let item = data.json[i];
            // if (item.skip_type=='' || item.skip_url == '') {
            //     this.$Message.error("请填写完整跳转信息");
            //     return;
            // }
          }
        } else if (parms.label_type == "popupChannel") {
          for (let i = 0; i < data.json.length; i++) {
            console.log(data.json[i],data.json[i].start_time == null,data.json[i].start_time == '',data.json[i].end_time == null,data.json[i].end_time == "")
            if (
              data.json[i].start_time == null ||
              data.json[i].start_time == "" ||
              data.json[i].end_time == null ||
              data.json[i].end_time == ""
            ) {
              this.$Message.error("请配置完整弹窗显示时间");
              return;
            }
          }
        }else if (parms.label_type == "goodsAlbumChannel") {
          // 商品合辑
          // if (data.json[0].more && data.json[0].more.display=="true" && (data.json[0].skip_type == '' || data.json[0].skip_url == '')) {
          //     this.$Message.error("请填写完整跳转信息");
          //     return;
          // }
        } else {
          if (
            parms.label_type == "normalChannel" ||
            parms.label_type == "goodsList" ||
            parms.label_type == "slideChannel"
          ) {
            if (data.label_goods == "") {
              this.$Message.error("请选择展示商品");
              return;
            }
          }
          // if (data.json.more && data.json.more.display && (data.json.more.skip_type == '' || data.json.more.skip_url == '')) {
          //     this.$Message.error("请填写完整跳转信息");
          //     return;
          // }
        }

        // 判断企业或商品个数是否5-10
        if (data.isRank) {
          for (var i = 0; i < data.json.length; i++) {
            if (
              data.json[i].goods.split(",").length < 5 ||
              data.json[i].goods.split(",").length > 10
            ) {
              this.$Message.error(
                data.json[i].rankType == "goods"
                  ? "选择5-10个商品"
                  : "选择5-10个企业"
              );
              return;
            }
          }
        }
        that.spinShow = true;
        updateEdit(parms)
          .then(_res => {
            this.$Message.success("保存组件成功");
            getPreviewData({ labelId: this.micro_id })
              .then(_res => {
                that.spinShow = false;
                this.componentList = _res.data;
              })
              .catch(err => {
                that.spinShow = false;
                this.$Message.error(err.message + " 请重新刷新页面");
              });
          })
          .catch(err => {
            that.spinShow = false;
            this.$Message.error(err.message);
          });
      }
    },

    // 比较版本
    compareVersion(v1, v2) {
      if (!v1 || !v2) {
        return false;
      }

      v1 = v1.split(".");
      v2 = v2.split(".");
      let len = Math.max(v1.length, v2.length);

      while (v1.length < len) {
        v1.push("0");
      }
      while (v2.length < len) {
        v2.push("0");
      }

      for (let i = 0; i < len; i++) {
        let num1 = parseInt(v1[i]);
        let num2 = parseInt(v2[i]);

        if (num1 > num2) {
          return true;
        } else if (num1 < num2) {
          return false;
        }
      }
      return true;
    }
  },
  created() {
    this.getData();
    if (this.micro_id != "index") {
      this.components.push({
        title: "商品列表",
        type: "goodsList"
      });
    }
  },
  computed: {
    // 微页面id index为首页
    micro_id: function() {
      var micro = this.$route.params.id ? this.$route.params.id : "index";
      if (micro != "index") {
        // 微页面
        this.label_index = -1;
      }
      return micro;
    },
    // 预览路径
    preview_path: function() {
      return this.$route.params.id
        ? "app/mall/label/label?labelId=" + this.$route.params.id
        : "app/mallA/index/index";
    }
  },
  watch: {
    // 监听路由变化 处理从微页面切换到首页的情况
    $route(to, from) {
      if (
        to.path == "/mall/renovation/index" &&
        from.path.indexOf("/mall/renovation/micropage") > -1
      ) {
        // 微页面切回首页
        this.label_index = 0;
        this.getData();
      } else {
        // 首页回退微页面 刷新避免页面数据错乱
        this.getData();
      }
    }
  },
  components: {
    draggable,
    TopTitleModule,
    BannerModule,
    ActivityModule,
    NormalModule,
    GoodsListModule,
    SecondKillModule,
    GroupModule,
    TalentModule,
    ImageModule,
    GoodsAlbumModule,
    SearchModule,
    TextModule,
    SliderModule,
    RankModule,
    ClassModule,
    SuspensionModule,
    LotteryModule,
    EditCommonModule,
    DistanceChannelModule,
    NoticeModule,
    bargainModule,
    LuckdrawModule,
    PopupModule
  }
};
</script>

<style lang='less' scoped>
#homepage-wrapper {
  background: #f8f8f8;
  width: 100%;
  padding: 12px 20px 12px 12px;
  height: calc(100vh - 64px);
  position: relative;
}

/* 内容 */
.content {
  height: 100%;
  width: 100%;
  overflow-x: auto;
}

/* 左边内容开始 */
.left-content {
  width: 250px;
  min-width: 250px;
  border-right: 1px solid #dcdfe6;
  background: white;
  overflow-y: auto;
}
.left-content::-webkit-scrollbar {
  width: 0;
  height: 0;
}
.left-content p {
  font-size: 14px;
  text-align: center;
}
.left-content .top-title {
  text-align: center;
  font-size: 14px;
  line-height: 16px;
  font-weight: bolder;
  padding: 20px 0 0 0;
  color: #262626;
  // border-bottom: 1px solid #e7eaec;
}
.qcode-wrapper {
  margin: 20px 65px 20px 65px;
  height: 124px;
  text-align: center;
  background-repeat: no-repeat;
  background-size: 124px 124px;
  background-position: center;
}

/* 组件添加按钮 */
.component-wrapper {
}
.component-wrapper p {
  width: 100%;
  font-size: 16px;
  font-weight: bold;
  padding: 10px;
  border-top: 4px solid #dcdee2;
  border-bottom: 1px solid #dcdee2;
  //   margin-top: 10px;
}
.item-wrapper {
  text-align: center;
  margin-bottom: 10px;
}
.item-wrapper button {
  min-width: 80px;
}
/* 左边内容结束 */

/* 中间内容开始 */
.middle-content {
  background: white;
  min-width: 360px;
  width: 360px;
  height: 100%;
  margin-left: 12px;
  margin-right: 12px;
  //border-right: 1px solid #dcdfe6;
  padding: 12px;
}

/* 组件预览内容 */
.middle-content .component-detail {
  position: relative;
  width: 100%;
  height: 100%;
  border: 1px solid rgb(248, 248, 248);
  overflow-y: auto;
  transition: all 2s ease;
}

/* 中间内容结束 */

/* 右边内容开始 */
.right-content {
  min-width: 500px;
  flex: 1;
  height: 100%;
  background: white;
  position: relative;
}
.item-detail {
  height: 100%;
}
.select-wrapper {
  width: 90px;
  margin-right: 10px;
}
/*预览内容编辑*/
.item-title {
  color: #262626;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 16px;
  line-height: 1;
  padding: 16px 24px;
  border-bottom: 1px solid #f2f2f2;
}
.input-wrapper {
  width: 70%;
}
/* 右边内容结束 */

.wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.component-wrapper {
  flex: 1;
}
.btn-save-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  border-top: 1px solid #f2f2f2;
}
.btn-save {
  color: #fff;
  background-color: #2d8cf0;
  border-color: #2d8cf0;
  padding: 6px 30px 6px 30px;
  font-size: 14px;
  border-radius: 4px;
}

/* class="for-column" 进行竖形排列  by wangwj */
.for-column {
  flex-direction: column;
}
/* 新自定义组件样式 by wangwj*/
.component-title {
  width: 100%;
}
.component-title .title-block {
  margin: 20px 9px 0px 10px;
  font-size: 14px;
  font-family: PingFang-SC-Bold;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: black;
}
.component-con {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.component-con .con-block {
  width: 110px;
  height: 110px;
  background: rgba(248, 248, 248, 1);
  border: 1px solid rgba(238, 238, 238, 1);
  margin: 10px 0px 0 10px;
}
.con-block .title-block {
  padding: 10px 7px 2px 7px;
  font-size: 12px;
  font-family: MicrosoftYaHei;
  font-weight: 600;
  color: rgba(51, 51, 51, 1);
  display: flex;
  justify-content: space-between;
}
.con-block .con-img {
  width: 100%;
  height: 74px;
}
.component-con .con-block:hover {
  border: 1px solid #2d8cf0;
  background: rgba(242, 248, 255, 1);
  cursor: pointer;
}
.component-con .con-block:active {
  box-shadow: 0 0 5px #2d8cf0;
}
</style>

